package com.wjc.myktapplication.cusview.paging.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.wjc.myktapplication.R
import com.wjc.myktapplication.databinding.NetworkStateItemBinding

class PostsLoadStateAdapter : LoadStateAdapter<NetworkStateItemViewHolder>() {
    override fun onBindViewHolder(holder: NetworkStateItemViewHolder, loadState: LoadState) {
        holder.bindTo(loadState)
    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): NetworkStateItemViewHolder {
        return NetworkStateItemViewHolder(parent)
    }
}

class NetworkStateItemViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.network_state_item, parent, false)) {

    private val binding = NetworkStateItemBinding.bind(itemView)
    private val progressBar = binding.progressBar
    private val errorMsg = binding.errorMsg

    fun bindTo(loadState: LoadState) {
        progressBar.isVisible = loadState is LoadState.Loading
        if (loadState is LoadState.Error) {
            errorMsg.isVisible = loadState.error.message.isNullOrBlank()
            errorMsg.text = loadState.error.message
        }
    }
}